/**
 * 备份恢复测试脚本 - 测试完整的备份和恢复流程
 */
require('dotenv').config();
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs');
const { spawn, execSync } = require('child_process');
const moment = require('moment');
const config = require('../src/config/config');
const backupService = require('../src/services/backup.service');
const { BackupSetting, Backup } = require('../src/models');

// JWT令牌 - 用于API测试
// 注意：实际测试时需要替换为有效的令牌
const JWT_TOKEN = process.env.TEST_JWT_TOKEN || '替换为有效的JWT令牌';
const API_URL = 'http://localhost:3000/api/v1';

// 连接数据库
mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => {
  console.log('成功连接到MongoDB');
  runTest();
}).catch(err => {
  console.error('MongoDB连接失败:', err);
  process.exit(1);
});

// 测试创建备份记录
async function testCreateBackupRecord() {
  try {
    console.log('创建测试备份记录...');
    
    // 确保备份目录存在
    const backupDir = path.join(__dirname, '../backups');
    if (!fs.existsSync(backupDir)) {
      fs.mkdirSync(backupDir, { recursive: true });
    }
    
    // 创建测试备份文件
    const timestamp = moment().format('YYYY-MM-DD_HH-mm-ss');
    const backupFileName = `test_record_${timestamp}.json`;
    const relativePath = `/backups/${backupFileName}`;
    const fullPath = path.join(__dirname, '../', relativePath);
    
    // 写入简单的JSON数据
    const testData = {
      metadata: {
        exportDate: new Date(),
        version: '1.0',
        database: mongoose.connection.name,
        test: true
      },
      message: '这是一个测试备份记录'
    };
    
    fs.writeFileSync(fullPath, JSON.stringify(testData, null, 2));
    
    // 计算文件大小（KB）
    const stats = fs.statSync(fullPath);
    const fileSize = Math.ceil(stats.size / 1024);
    
    // 创建备份记录
    const backup = await Backup.create({
      type: 'manual',
      fileSize,
      status: 'success',
      filePath: relativePath,
    });
    
    console.log(`创建测试备份记录成功，ID: ${backup._id}`);
    console.log(`文件路径: ${fullPath}`);
    console.log(`文件大小: ${fileSize}KB`);
    
    return backup;
  } catch (error) {
    console.error('创建测试备份记录失败:', error);
    return null;
  }
}

// 通过API测试下载备份
async function testBackupDownload(backupId) {
  try {
    console.log(`\n测试备份下载API (ID: ${backupId})...`);
    
    // 构建下载URL
    const downloadUrl = `${API_URL}/settings/backups/${backupId}/download`;
    console.log(`下载URL: ${downloadUrl}`);
    
    console.log('API下载测试需要手动验证:');
    console.log(`1. 在浏览器中打开下载URL: ${downloadUrl}`);
    console.log('2. 添加Authorization头: Bearer YOUR_JWT_TOKEN');
    console.log('3. 验证文件是否正确下载');
    
    return true;
  } catch (error) {
    console.error('测试备份下载失败:', error);
    return false;
  }
}

// 执行真实备份操作
async function testRealBackup() {
  try {
    console.log('\n测试真实备份操作...');
    const backup = await backupService.executeBackup('manual');
    
    console.log(`真实备份创建成功，ID: ${backup._id}`);
    console.log(`文件路径: ${backup.filePath}`);
    console.log(`文件大小: ${backup.fileSize}KB`);
    
    return backup;
  } catch (error) {
    console.error('真实备份创建失败:', error);
    return null;
  }
}

// 检查备份列表API
async function testBackupListAPI() {
  try {
    console.log('\n测试备份列表API...');
    
    // 通过mongoose直接获取备份数量
    const backupCount = await Backup.countDocuments({ isDeleted: false });
    console.log(`数据库中有 ${backupCount} 个备份记录`);
    
    console.log('API列表测试需要手动验证:');
    console.log(`1. 访问备份列表API: ${API_URL}/settings/backups`);
    console.log('2. 添加Authorization头: Bearer YOUR_JWT_TOKEN');
    console.log('3. 验证返回的备份列表是否完整');
    
    return true;
  } catch (error) {
    console.error('测试备份列表API失败:', error);
    return false;
  }
}

// 运行所有测试
async function runTest() {
  try {
    console.log('开始测试备份和恢复功能...');
    
    // 测试1: 创建测试备份记录
    const testBackup = await testCreateBackupRecord();
    
    if (testBackup) {
      // 测试2: 测试备份下载
      await testBackupDownload(testBackup._id);
      
      // 测试3: 执行真实备份
      const realBackup = await testRealBackup();
      
      // 测试4: 检查备份列表API
      await testBackupListAPI();
      
      console.log('\n所有测试完成!');
      console.log('备份功能验证结果: ✅ 通过');
      console.log('\n注意:');
      console.log('1. 下载和API列表测试需要手动验证');
      console.log('2. 恢复功能需要手动测试，避免意外覆盖数据库');
    } else {
      console.log('\n测试失败: 无法创建测试备份记录');
    }
    
    // 断开数据库连接
    mongoose.disconnect();
  } catch (error) {
    console.error('测试过程出错:', error);
    mongoose.disconnect();
  }
} 